/**
 * @class 计时器系统
 * @author DuskyHuang 圣子
 * @description 管理系统记时（S）
*/

import { _decorator, director, System, game, Game } from 'cc';
import { singleton } from '../../utils/decorators';
import { Notifications } from '../../configs';
import { EDITOR } from "cc/env";
import { notifier } from '../boot';
const { TICK, SECOND, MINUTE, SPAN, POST_TICK } = Notifications.Time;

@singleton
export default class TimerSystem extends System {

    declare public static readonly instance: TimerSystem;

    /** 
     * 时间段
     * @explain 时段长短的设置：TimerSystem.span = num
     * @explain 监听时间段事件：core.on(Notifications.Time.SPAN, handler, observer);
     */
    public span: time.sec = 0;

    public static readonly ID = 'Timer';
    private _tick: time.sec = 0;
    private _elapse: time.sec = 0;
    private _seconds: time.sec = 0;
    private _minutes: time.min = 0;
    private _past: time.sec = 0;
    private _num: number = 0

    public update(dt: number): void {
        notifier.dispatch(TICK, dt, ++this._tick);
        this._elapse += dt;
        if (this._elapse >= 1) {
            this._elapse -= 1;
            notifier.dispatch(SECOND, dt, ++this._seconds);
            if (this._seconds >= 60) {
                notifier.dispatch(MINUTE, this._minutes += 1);
            }
        }
        if (this.span > 0) {
            this._past += dt;
            if (this._past >= this.span) {
                this._past -= this.span;
                notifier.dispatch(SPAN, dt, ++this._num);
            }
        }
    }

    public postUpdate(dt: number): void {
        notifier.dispatch(POST_TICK, dt, this._tick);
    }
}

if (!EDITOR) {
    game.on(Game.EVENT_GAME_INITED,
        () => director.registerSystem(TimerSystem.ID, TimerSystem.instance, 0));
}